﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.Database;
using MySQL.Db;

namespace Gollie.Controls
{
	public partial class EditOffer : AuthenticationRequiredSalesBaseUserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			uint offerId;

			try
			{
				offerId = Convert.ToUInt32(Request["o"]);

				ResultSet r = Queries.GetVendorOfferForEdit(this.UserInfo, offerId);

				this.Populate(r);
			}
			catch (Exception ex)
			{
				logger.FatalException("Editoffer.aspx: {0}", ex);
				Response.Redirect("Expired.aspx", true);
			}
		}

		private void Populate(ResultSet r)
		{
			int numberSold = r.GetInt32(0, "numbersold");

			this.lblAanmaakDatum.Text = ObjectFormatter.GetFormattedTimeStamp(r.GetDateTime(0, "entrydate"));
			this.lblCreator.Text = UserInfo.GetFullName(r.GetString(0, "initials"), r.GetString(0, "infix"), r.GetString(0, "lastname"));
			this.lblCredit.Text = ObjectFormatter.GetCurrencyString(r.GetDecimal(0, "credit"));

			uint expires = r.GetUInt32(0, "expiresafter");
			this.lblExpiresAfter.Text = ObjectFormatter.GetDurationString((int)expires);
			this.lblNumberSold.Text = numberSold.ToString();
			this.lblPrice.Text = ObjectFormatter.GetCurrencyString(r.GetDecimal(0, "price"));
			this.lblValidFrom.Text = ObjectFormatter.GetDateString(r.GetDateTime(0, "validfrom"));
			this.tbDescription.Text = r.GetString(0, "description");
			this.tbNumbermax.Text = r.GetString(0, "numbermax");
			this.tbValidTo.Text = ObjectFormatter.GetShortDateString(r.GetDateTime(0, "validto"));
		}

		protected override void OnPostBack(object sender, EventArgs e)
		{
			StringCollection errors = this.ValidateAndRegister();
			if (errors.Count > 0)
			{
				StringBuilder str = new StringBuilder();
				str.Append("Het formulier bevat de volgende fouten:");
				str.Append("<ul>");
				foreach (string err in errors)
				{
					str.Append("<li>");
					str.Append(err);
					str.Append("</li>");
				}
				str.Append("</ul");

				this.ErrorMessageControlTotal.Text = str.ToString();
				this.ErrorMessageControlTotal.Show();
			}
			else
				this.Response.Redirect("/MyVendorOffers.aspx");

		}

		private StringCollection ValidateAndRegister()
		{
			uint offerId = 0;
			int numberSold = 0;
			ResultSet r = null;

			try
			{
				offerId = Convert.ToUInt32(Request["o"]);

				r = Queries.GetVendorOfferForEdit(this.UserInfo, offerId);

				numberSold = r.GetInt32(0, "numbersold");
				this.lblNumberSold.Text = numberSold.ToString();

			}
			catch (Exception ex)
			{
				logger.FatalException("Editoffer.aspx: {0}", ex);
				Response.Redirect("Expired.aspx", true);
			}

			StringCollection errors = new StringCollection();

			int aantal = 0;

			try
			{
				aantal = this.tbNumbermax.IntValue;
				if (aantal < 0)
					errors.Add("Het maximum aantal moet groter of gelijk zijn aan 0");
			}
			catch (FormatException)
			{
				errors.Add("Maximum aantal foutief formaat");
			}

			if (aantal != 0 && aantal < numberSold)
				errors.Add("Het maximum aantal moet groter of gelijk zijn aan het reeds verkochte aantal");

			DateTime ingangsDatum = DateTime.MinValue;
			try
			{
				ingangsDatum = r.GetDateTime(0, "validfrom");
			}
			catch (Exception)
			{
				errors.Add("Ingangsdatum foutief formaat (dd-mm-jjjj)");
			}

			DateTime stopDatum;
			if (DateTime.TryParse(this.tbValidTo.Text, out stopDatum) == false)
			{
				errors.Add("Afloop datum foutief formaat (dd-mm-jjjj)");
			}
			else
			{
				if (stopDatum.Date <= ingangsDatum.Date)
				{
					errors.Add("De afloopdatum moet na de ingangsdatum liggen");
				}

				if (stopDatum <= DateTime.Today)
				{
					errors.Add("De afloopdatum moet in de toekomst liggen");
				}
			}

			if (errors.Count == 0)
			{
				try
				{
					Database.Queries.UpdateOffer(offerId, aantal, stopDatum);
				}
				catch (MySql.Data.MySqlClient.MySqlException ex)
				{
					errors.Add(MySqlErrorCodes.GetInstance().GetMessage(ex));
				}
			}

			return errors;
		}
	}
}